//
//  BottomToolbar.m
//  MoneyIndividual
//
//  Created by Tai Le on 1/2/14.
//  Copyright (c) 2014 Le Anh Tai. All rights reserved.
//

#import "BottomToolbar.h"

@implementation BottomToolbar

- (id)initWithTitles:(NSArray *)titles
{
    self = [super init];
    
    if (self)
    {
        _buttons = [[NSMutableArray alloc] init];
        _lineViews = [[NSMutableArray alloc] init];
        
        if (titles && [titles isKindOfClass:[NSArray class]])
        {
            for (int i = 0; i < titles.count; i++)
            {
                NSString *title = [titles objectAtIndex:i];
                UIButton *button = [UIButton buttonWithTitle:title target:self selector:@selector(buttonPressed:)];
                button.tag = i;
                [self addSubview:button];
                
                if (i > 0)
                {
                    //add separator
                    UIView *lineView = [UIView newLineView];
                    [self addSubview:lineView];
                    [_lineViews addObject:lineView];
                }
                
                [_buttons addObject:button];
            }
            
            _numberOfTitle = titles.count;
        }
        
        if (_numberOfTitle == 0)
        {
            _numberOfTitle = 1;
        }
        
        _lineTop = [UIView newLineView];
        [self addSubview:_lineTop];
    }
    
    return self;
}

- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    
    int lineWid = 1;
    
    [_lineTop setFrame:RECT(0, 0, self.width, lineWid)];
    
    int left = 0;
    int wid = (self.width - (_numberOfTitle - 1)*lineWid) / _numberOfTitle;
    for (int i = 0; i < _buttons.count; i ++)
    {
        UIButton *button = [_buttons objectAtIndex:i];
        button.frame = RECT(left, 0, wid, self.height);
        
        left = button.right;
        
        if (i < _lineViews.count)
        {
            UIView *lineView = [_lineViews objectAtIndex:i];
            lineView.frame = RECT(left, 0, lineWid, self.height);
            
            left = lineView.right;
        }
    }
}

- (void)buttonPressed:(UIButton*)sender
{
    if ([_delegate respondsToSelector:@selector(bottomToolbar:didPressedButtonAtIndex:)])
    {
        [_delegate bottomToolbar:self didPressedButtonAtIndex:sender.tag];
    }
}

@end
